package com.originskyseed.platform.user.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.user.i18n.UserResponseMsg;
import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.model.ParameterConfigure;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IDeptService;
import com.originskyseed.platform.user.service.IParameterConfigureService;
import com.originskyseed.platform.user.service.IUserInfoService;
import com.originskyseed.platform.user.vo.request.DeptRequestVO;

/**
 * 部门表Controller类（OSI_DEPT）
 * 
 * @author Tangwanghui
 */
@Controller
@RequestMapping("/dept")
@BaseLocaleResource(localeFileName = "i18n_user")
public class DeptController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(DeptController.class);

	@DubboReference
	private IDeptService deptService;

	@DubboReference
	private IUserInfoService userInfoService;

	@DubboReference
	private IParameterConfigureService parameterConfigureService;

	/**
	 * 分页查询
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/deptList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<Dept>> deptList(HttpServletRequest request) {
		BaseResponseBody<BasePage<Dept>> result = null;
		try {
			// 当前登录用户
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
            if(userInfo==null)
			{
				result = new BaseResponseBody<BasePage<Dept>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()),null, null);
				return  result;
			}
			// 请求对象
			DeptRequestVO requestVO = this.getParameterBean(DeptRequestVO.class);
			requestVO.setIsDel(0);
			Map<String, Object> map = requestVO.toMap();
			// 获得所有的子部门
			List<String> array = new ArrayList<>();
			Dept dept = this.deptService.selectByPrimaryKey(userInfo.getDeptId());
			if(dept!=null) {
				array.add(dept.getCode());
				this.selectSonCode(dept.getCode(), array);
				map.put("array", array);
			}

			// 分页查询
			BasePage<Dept> page = new BasePage<Dept>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.deptService.selectListByPage(map, page);
			result = new BaseResponseBody<BasePage<Dept>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<Dept>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/deptSave.json", method = RequestMethod.POST)
	@RequiredParams(names = { "name", "sourceSys" })
	public BaseResponseBody deptSave(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 请求对象
			Dept dept = this.getParameterBean(Dept.class);

			// 判断所属平台
			Dept parentDept = this.deptService.selectByCode(dept.getParentCode());
			if (dept.getSourceSys() != null&&parentDept!=null&&parentDept.getSourceSys()!=null) {
				// 如果不是自建下面的，则子部门必须和父部门的所在平台一样
				if (dept.getSourceSys() != parentDept.getSourceSys() && !(parentDept.getSourceSys() == 0 && parentDept.getType() == -1)) {
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.SON_PARENT_NOT_EQUALLY_ERROR.getMsg()), false);
				}
			} else {
				if(parentDept!=null){
					dept.setSourceSys(parentDept.getSourceSys());
				}else {
					dept.setSourceSys(0);
				}
			}

			if (StringUtils.isNotBlank(dept.getId())) {
				this.deptService.updateByPrimaryKey(dept);
			} else {
				// 新增时父编码不能为空
				if(StringUtils.isBlank(dept.getParentCode())){
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DEPT_PARENT_CODE_ISNULL_ERROR.getMsg()), false);
				}
				Integer prority = this.deptService.selectPrority();
				if (prority == null) {
					dept.setPriority(0);
				} else {
					dept.setPriority(prority + 1);
				}

				if (parentDept != null && parentDept.getType() != null) {
					dept.setType(parentDept.getType() + 1);
				} else {
					dept.setType(-1);
				}

				dept.setIsDel(0);
				dept.setIsTop(0);
				dept.setCreatorId(userInfo.getId());
				dept.setCreator(userInfo.getName());
				dept.setCode(this.deptService.selectDeptCode());
				this.deptService.insertSelective(dept);
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), dept);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/deptDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> deptDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});
			for (String id : ids) {
				if (this.deptService.selectExistSon(id)) {
					return new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.EXIST_SON_DEPT_ERROR.getMsg()), null);
				}
				if (this.userInfoService.selectUserNumByDeptId(id) > 0) {
					return new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.EXIST_USER_ERROR.getMsg()), null);
				}
			}
			this.deptService.updateIsDel(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 加载部门管理树
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/deptTree.json")
	public BaseResponseBody deptTree(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 来源 1 内容 2 推广
			Integer sourceSys = this.getParameterInteger("sourceSys", null);
			JSONArray deptTree = null;
			if (sourceSys != null) {
				deptTree = this.deptService.selectDeptTreeList(sourceSys);
			} else {
				deptTree = this.deptService.selectDeptTreeList();
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), deptTree);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 批量禁用部门
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateStatus.json")
	@RequiredParams(names = { "ids", "status" })
	public BaseResponseBody updateStatus(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			String[] ids = this.getParameterArray("ids", null);
			Integer status = this.getParameterInteger("status", null);
			Map<String, Object> map = new HashMap<>();
			map.put("list", Arrays.asList(ids));
			map.put("status", status);
			this.deptService.updateStatusByIds(map);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 根据id查询详情
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectDeptById.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id" })
	public BaseResponseBody selectDeptById(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);

			Dept dept = this.deptService.selectByPrimaryKey(id);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_SUCCESS.getMsg()), dept);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询全部部门列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectDeptList.json", method = RequestMethod.POST)
	public BaseResponseBody selectDeptList(HttpServletRequest request) {
		BaseResponseBody<BasePage<Dept>> result = null;
		try {
			// 请求对象
			Dept dept = this.getParameterBean(Dept.class);
			List<Dept> deptList = this.deptService.selectList(dept);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), deptList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 修改置顶信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateIsTop.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id" })
	public BaseResponseBody updateIsTop(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);
			Integer prority = this.deptService.selectPrority();

			Dept dept = new Dept();
			dept.setId(id);
			dept.setIsTop(1);
			dept.setPriority(prority + 1);

			this.deptService.updateIsTop(dept);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 升序降序
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateUpOrDown.json")
	@RequiredParams(names = { "id", "upOrDown", "prority" })
	public BaseResponseBody updateUpAndDown(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);
			Integer upOrDown = this.getParameterInteger("upOrDown", null);

			// 查询出优先级
			Dept queryDept = this.deptService.selectByPrimaryKey(id);
			Integer priority = queryDept.getPriority();

			Map<String, Object> map = new HashMap<>();
			map.put("type", upOrDown);
			map.put("priority", priority);
			// 将另外一个升序或降序
			Dept dept = this.deptService.selectDeptByProritySort(map);

			Dept updateDept = new Dept();
			updateDept.setId(id);
			if (dept != null) {
				updateDept.setPriority(dept.getPriority());
				dept.setPriority(priority);
			} else {
				// 等于0是升序 1是降序
				if (upOrDown == 0) {
					updateDept.setPriority(priority + 1);
				} else {
					updateDept.setPriority(priority - 1);
				}
			}

			if (dept != null) {
				this.deptService.updatePrority(dept, updateDept);
			} else {
				this.deptService.updateByPrimaryKeySelective(updateDept);
			}

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_ORDER_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_ORDER_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询查看范围
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectViewRange.json", method = RequestMethod.POST)
	@RequiredParams(names = { "type" })
	public BaseResponseBody selectViewRange(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数 0 公司 1 部门 2 岗位
			Integer type = this.getParameterInteger("type", null);

			List<Map<String, Object>> list = new ArrayList<>();
			if (type == 1) {
				Dept queryDept = new Dept();
				queryDept.setType(2);
				List<Dept> deptList = this.deptService.selectList(queryDept);
				for (Dept dept : deptList) {
					Map<String, Object> map = new HashMap<>();
					map.put("id", dept.getId());
					map.put("name", dept.getName());
					list.add(map);
				}
			} else if (type == 2) {
				JSONArray jsonArray = this.deptService.selectDeptTreeList();
				return new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), jsonArray);
			} else if (type == 3) {
				String code = "EMPLOYEE_POSITION";
				ParameterConfigure parameterConfigure = this.parameterConfigureService.selectByCode(code);
				if (parameterConfigure != null) {
					ParameterConfigure query = new ParameterConfigure();
					query.setParentId(parameterConfigure.getId());
					List<ParameterConfigure> parameterConfigureList = this.parameterConfigureService.selectList(query);
					for (ParameterConfigure parameterConfigure1 : parameterConfigureList) {
						Map<String, Object> map = new HashMap<>();
						map.put("id", parameterConfigure1.getId());
						map.put("code",parameterConfigure1.getCode());
						map.put("name", parameterConfigure1.getName());
						list.add(map);
					}
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), list);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}


	/**
	 * 根据岗位查询用户列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectUserByStation.json", method = RequestMethod.POST)
	public BaseResponseBody selectUserByStation(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数 岗位id
			String id = this.getParameterString("id", null);
			List<UserInfo> userInfoList = new ArrayList<>();

			// 查询配置参数
			ParameterConfigure parameterConfigure = this.parameterConfigureService.selectByPrimaryKey(id);
			if (parameterConfigure != null) {
				int type = Integer.parseInt(parameterConfigure.getCode());
				UserInfo query = new UserInfo();
				query.setType(type);
				query.setIsDel(0);
				query.setStatus(1);
				query.setIsQuit(0);
				userInfoList = this.userInfoService.selectList(query);
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), userInfoList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 加载当前用户部门树
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/selectUserDeptTree.json")
	public BaseResponseBody selectUserDeptTree(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// type 0 查询业务员 1 不查询业务员
			Integer type = this.getParameterInteger("type",0);
			// 当前登录用户
			UserInfo currentUserInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);

			// 返回的集合
			JSONArray jsonArray = new JSONArray();
			if (currentUserInfo != null && StringUtils.isNotBlank(currentUserInfo.getDeptId())) {
				Dept dept = this.deptService.selectByPrimaryKey(currentUserInfo.getDeptId());
				if (dept != null) {
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("id", dept.getId());
					jsonObject.put("code", dept.getCode());
					jsonObject.put("parentCode", dept.getParentCode());
					jsonObject.put("name", dept.getName());
					jsonObject.put("sourceSys", dept.getSourceSys());
					jsonObject.put("type", dept.getType());
					//int userNum = this.userInfoService.selectUserNumByStatusDeptId(dept.getId());
					//jsonObject.put("userNum",userNum);

					// 查询业务员
					if(type==0 && dept.getSourceSys()==2){
						UserInfo query = new UserInfo();
						query.setDeptId(dept.getId());
						query.setType(6);
						List<UserInfo> userInfoList = this.userInfoService.selectList(query);
						JSONArray array = new JSONArray();
						for (UserInfo userInfo : userInfoList) {
							JSONObject jsonObject1 = new JSONObject();
							jsonObject1.put("id", userInfo.getId());
							jsonObject1.put("code", userInfo.getId());
							jsonObject1.put("parentCode", dept.getCode());
							jsonObject1.put("name", userInfo.getName());
							jsonObject1.put("sourceSys", dept.getSourceSys());
							jsonObject1.put("type", 6);
							array.add(jsonObject1);
						}
						jsonObject.put("children", array);
						// 查询主播
					}else if(type == 0 && dept.getSourceSys()==1){
						UserInfo query = new UserInfo();
						query.setDeptId(dept.getId());
						query.setType(11);
						List<UserInfo> userInfoList = this.userInfoService.selectList(query);
						JSONArray array = new JSONArray();
						for (UserInfo userInfo : userInfoList) {
							JSONObject jsonObject1 = new JSONObject();
							jsonObject1.put("id", userInfo.getId());
							jsonObject1.put("code", userInfo.getId());
							jsonObject1.put("parentCode", dept.getCode());
							jsonObject1.put("name", userInfo.getName());
							jsonObject1.put("sourceSys", dept.getSourceSys());
							jsonObject1.put("type", 4);
							array.add(jsonObject1);
						}
						jsonObject.put("children", array);
					}

					this.deptService.selectUserDeptTreeList(dept, jsonObject,type);
					// 计算当前部门下的员工数量
					//JSONObject numObject = new JSONObject();
					//numObject.put("num",userNum);
					//getUserNum(jsonObject,numObject);
					//jsonObject.put("num",numObject.get("num"));
					// 计算当前部门下所以部门的员工数量
					//this.calculationUserNum(jsonObject);
					jsonArray.add(jsonObject);
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), jsonArray);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}


	/**
	 * 加载当前用户部门树,只加载二级
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/selectNewUserDeptTree.json")
	public BaseResponseBody selectNewUserDeptTree(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// type 0 查询业务员 1 不查询业务员
			Integer type = this.getParameterInteger("type",0);
			// 当前登录用户
			UserInfo currentUserInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 返回的集合
			JSONArray jsonArray = new JSONArray();
			if (currentUserInfo != null && StringUtils.isNotBlank(currentUserInfo.getDeptId())) {
				Dept dept = this.deptService.selectByPrimaryKey(currentUserInfo.getDeptId());
				if (dept != null) {
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("id", dept.getId());
					jsonObject.put("deptId",dept.getId());
					jsonObject.put("code", dept.getCode());
					jsonObject.put("parentCode", dept.getParentCode());
					jsonObject.put("name", dept.getName());
					jsonObject.put("sourceSys", dept.getSourceSys());
					jsonObject.put("type", dept.getType());
					jsonObject.put("num",selectUserNumByDeptId(dept.getId(),dept.getCode()));
					jsonObject.put("isHaveChildren",this.deptService.selectIsHaveChildren(dept.getId(),dept.getCode()));

					// 查询下级部门
					List<Dept> deptList = this.deptService.selectByParentCode(dept.getCode());
					JSONObject obj = null;
					JSONArray sonJsonArray = new JSONArray();
					if (deptList != null && deptList.size() > 0) {
						sonJsonArray = new JSONArray();
						for (Dept sonDept : deptList) {
							obj = new JSONObject();
							obj.put("id", sonDept.getId());
							obj.put("deptId",dept.getId());
							obj.put("code", sonDept.getCode());
							obj.put("parentCode", sonDept.getParentCode());
							obj.put("name", sonDept.getName());
							obj.put("sourceSys", sonDept.getSourceSys());
							obj.put("type", sonDept.getType());
							obj.put("num",selectUserNumByDeptId(sonDept.getId(),sonDept.getCode()));
							obj.put("isHaveChildren",this.deptService.selectIsHaveChildren(sonDept.getId(),sonDept.getCode()));
							sonJsonArray.add(obj);
						}
					}
					// 查询部门下的业务员或者主播 ，当type=0时
					if(type!=null && type == 0){
						selectSalesmanOrAnchor(dept,sonJsonArray);
					}
					jsonObject.put("children", sonJsonArray);
					jsonArray.add(jsonObject);
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), jsonArray);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 加载子部门列表
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/selectSonDeptList.json")
	@RequiredParams(names = { "deptId"})
	public BaseResponseBody selectSonDeptList(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// type 0 查询业务员 1 不查询业务员
			Integer type = this.getParameterInteger("type",0);
			String deptId = this.getParameterString("deptId",null);
			// 返回的集合
			JSONArray jsonArray = new JSONArray();
			Dept dept = this.deptService.selectByPrimaryKey(deptId);
			if (dept != null) {
				// 查询下级部门
				List<Dept> deptList = this.deptService.selectByParentCode(dept.getCode());
				JSONObject obj = null;
				if (deptList != null && deptList.size() > 0) {
					for (Dept sonDept : deptList) {
						obj = new JSONObject();
						obj.put("id", sonDept.getId());
						obj.put("deptId",sonDept.getId());
						obj.put("code", sonDept.getCode());
						obj.put("parentCode", sonDept.getParentCode());
						obj.put("name", sonDept.getName());
						obj.put("sourceSys", sonDept.getSourceSys());
						obj.put("type", sonDept.getType());
						obj.put("num",selectUserNumByDeptId(sonDept.getId(),sonDept.getCode()));
						obj.put("isHaveChildren",this.deptService.selectIsHaveChildren(sonDept.getId(),sonDept.getCode()));
						jsonArray.add(obj);
					}
				}
				// 查询部门下的业务员或者主播 ，当type=0时
				if(type!=null && type == 0){
					selectSalesmanOrAnchor(dept,jsonArray);
				}
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), jsonArray);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}


	/**
	 * 查询组织架构接口
	 * 
	 * @param code
	 * @param list
	 * @throws Exception
	 */
	private void selectSonCode(String code, List<String> list) throws Exception {
		List<Dept> deptList = this.deptService.selectByParentCode(code);
		if (deptList != null) {
			for (Dept dept1 : deptList) {
				list.add(dept1.getCode());
				selectSonCode(dept1.getCode(), list);
			}
		}
	}

	/**
	 * 查询业务员或主播信息
	 * @param dept
	 * @return
	 * @throws Exception
	 */
	private JSONArray selectSalesmanOrAnchor(Dept dept,JSONArray jsonArray) throws Exception{
		// 查询业务员
		UserInfo query = new UserInfo();
		query.setDeptId(dept.getId());
		query.setType(6);
		List<UserInfo> userInfoList = this.userInfoService.selectList(query);
		for (UserInfo userInfo : userInfoList) {
			JSONObject jsonObject1 = new JSONObject();
			jsonObject1.put("id", userInfo.getId());
			jsonObject1.put("code", userInfo.getId());
			jsonObject1.put("parentCode", dept.getCode());
			jsonObject1.put("name", userInfo.getName());
			jsonObject1.put("sourceSys", dept.getSourceSys());
			jsonObject1.put("type", 6);
			jsonArray.add(jsonObject1);
		}
		// 查询主播
		query.setDeptId(dept.getId());
		query.setType(11);
		userInfoList = this.userInfoService.selectList(query);
		for (UserInfo userInfo : userInfoList) {
			JSONObject jsonObject1 = new JSONObject();
			jsonObject1.put("id", userInfo.getId());
			jsonObject1.put("code", userInfo.getId());
			jsonObject1.put("parentCode", dept.getCode());
			jsonObject1.put("name", userInfo.getName());
			jsonObject1.put("sourceSys", dept.getSourceSys());
			jsonObject1.put("type", 4);
			jsonArray.add(jsonObject1);
		}
		return jsonArray;
	}

	/**
	 * 查询部门下用户数量
	 * @param deptId
	 * @param deptCode
	 * @return
	 * @throws Exception
	 */
	private int selectUserNumByDeptId(String deptId,String deptCode) throws Exception{
		// 部门id
		List<String> list = new ArrayList<>();
		list.add(deptId);
		this.selectSonId(deptCode,list);
		return this.userInfoService.selectUserNumByStatusDeptIds(list);
	}

	/**
	 * 查询组织架构接口
	 *
	 * @param code
	 * @param list
	 * @throws Exception
	 */
	private void selectSonId(String code, List<String> list) throws Exception {
		List<Dept> deptList = this.deptService.selectByParentCode(code);
		if (deptList != null) {
			for (Dept dept1 : deptList) {
				list.add(dept1.getId());
				selectSonId(dept1.getCode(), list);
			}
		}
	}
}